import { Component } from 'react'
import { View, Text } from '@tarojs/components'
import { Container,WqCommentBar } from "../components"
import { AtImagePicker, AtTabBar,AtAvatar,AtActionSheet, AtActionSheetItem,AtList, AtListItem,AtModal, AtModalHeader, AtModalContent, AtModalAction,AtButton,
    AtTextarea,
    AtToast,
    AtTimeline,
    AtRadio  } from 'taro-ui'
import { Picker } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { getCurrentInstance } from '@tarojs/taro'

import "taro-ui/dist/style/components/article.scss"
import "taro-ui/dist/style/components/flex.scss"

import './order-detail-other.scss'
import './order-detail.scss'

import "taro-ui/dist/style/components/card.scss"
import "taro-ui/dist/style/components/input.scss"
import "taro-ui/dist/style/components/image-picker.scss"
import "taro-ui/dist/style/components/icon.scss"
import "taro-ui/dist/style/components/tab-bar.scss"
import "taro-ui/dist/style/components/badge.scss"
import "taro-ui/dist/style/components/search-bar.scss";
import "taro-ui/dist/style/components/button.scss";
import "taro-ui/dist/style/components/article.scss"
import "taro-ui/dist/style/components/avatar.scss";
import "taro-ui/dist/style/components/action-sheet.scss";
import "taro-ui/dist/style/components/list.scss";
import "taro-ui/dist/style/components/modal.scss";
import "taro-ui/dist/style/components/loading.scss";
import "taro-ui/dist/style/components/textarea.scss";
import "taro-ui/dist/style/components/toast.scss";
import "taro-ui/dist/style/components/timeline.scss";
import "taro-ui/dist/style/components/radio.scss";

import {getOrderInfo, getOrderHand,upOrderLike,actionOrderPeroperHand,
    getGongdanImportanceLevel
} from "../api"
import Auth from "../../utils/auth"
import requestFileUpload from "../../utils/request-file-upload"

export default class OrderDetail extends Component {
    constructor () {
        super(...arguments)
        this.state = {
            gongdanImportanceLeve:[],
            hangState:false,
            handleWaitState:false,
            handleCompleteState:false,
            completeText:"",
            complletePics:[],
            pics:[],
            picsComplete:[],
            data:{},
            tabList:[],
            backgroundColor:"#fff",
            timeSel: '12:01',
            dateSel: '2018-04-22',
            toastState:false,
            toastText:"",
            hangePeoper:[],
            hangePeoperid:0,
            hangePeoperIsOpened:false
        }
    }
    formatDate(y){
        var myDate = new Date();
        if(y == "time"){
            let h = myDate.getHours();
            let m = myDate.getMinutes();
            if(h<10){
                h = "0"+h;
            }
            if(m<10){
                m = "0"+m;
            }
            return h+':'+m;
        }
        if(y == 'date'){
            let y = myDate.getFullYear();
            let m = myDate.getMonth()+1;
            let d = myDate.getDate();
            if(m<10){
                m = "0"+m;
            }
            if(d < 10){
                d = "0"+d;
            }
            return y+'-'+m+'-'+d;
        }
        
    }
    onTimeChange = e => {
        this.setState({
            timeSel: e.detail.value
        })
    }
    onDateChange = e => {
        this.setState({
            dateSel: e.detail.value
        })
    }
    
    async componentDidMount () {
        try {
            let resInit = await getGongdanImportanceLevel();    
            this.setState({
                gongdanImportanceLeve:resInit.data
            });
        } catch (error) {
            
        }
        
        
        let params = getCurrentInstance().router.params;
        if(params.id > 0){
            let res = await getOrderInfo(params.id);
            let picsComplete = [];
            if(res.data.detailList!=null && res.data.detailList.length>0){
                res.data.detailList.forEach(e=>{
                    if(e.opinionPics != null)
                        picsComplete = picsComplete.concat(e.opinionPics);
                })
            }
            this.setState({
                pics:res.data.pics===null?[]:res.data.pics,
                picsComplete:picsComplete,
                data: res.data,
                hangePeoper:res.data.mlist
            })
            let backgroundColor = "#fff";
            let openid = Auth.getOpenid();
            let tabList;
            

            //是否是一级管理员
            if(this.state.data.toOpenid == openid){
                if(this.state.data.statue === 0){
                    backgroundColor = "#6190e8";
                    tabList = [
                        { title: '开始处理',iconPrefixClass:'wq',iconType: 'fuwu', fontSize: '12px'}
                    ]
                }else if(this.state.data.statue === 1){
                    backgroundColor = "#ffc82c";
                    tabList = [
                        { title: '处理完成',iconPrefixClass:'wq',iconType: 'wancheng', fontSize: '12px'}
                    ]
                } 
            }
            else if(this.state.data.fromOpenid!=openid && this.state.data.toOpenid2 == openid){
                //二级管理员
                if(this.state.data.statue === 0){
                    backgroundColor = "#CDDC39";
                    tabList = [
                        { title: '切换处理人员',iconType: 'analytics'},
                    ]
                }
            }
            else if(this.state.data.statue == 2){
                // tabList = [
                //     { title: '评论',iconType: 'message'},
                //     { title: '点赞',iconType: 'heart'}
                // ]
                // if(this.state.data.isLiks > 0){
                //     tabList = [
                //         { title: '评论',iconType: 'message'},
                //         { title: '点赞',iconType: 'heart-2'}
                //     ]
                // }
                
            }else{
                tabList = [
                    { title: '新增',iconType: 'add'},
                    { title: '编辑', iconType: 'edit' },
                    // { title: '撤回', iconPrefixClass:'wq', iconType: 'arrow-go-back-line', fontSize: '12px' }
                ]
            }
            
            var timeSel =  this.formatDate("time");
            var dateSel = this.formatDate("date");
            this.setState({
                timeSel:timeSel,
                dateSel:dateSel,
                backgroundColor:backgroundColor,
                tabList:tabList
            })
        }
    }
    updateData(){
        this.componentDidMount();
    }
    onFail (mes) {
        console.log(mes)
    }
    onImageClick (index, file) {
        const imgurls = this.state.pics.map(item=>item.url);
        Taro.previewImage({
            current: file.url, // 当前显示图片的http链接
            urls: imgurls // 需要预览的图片http链接列表
          });
    }
    onImageClick2 (index, file) {
        const imgurls = this.state.complletePics.map(item=>item.url);
        Taro.previewImage({
            current: file.url, // 当前显示图片的http链接
            urls: imgurls // 需要预览的图片http链接列表
          });
    }
    onImageClick3(index,file) {
        const imgurls = this.state.picsComplete.map(item=>item.url);
        Taro.previewImage({
            current: file.url, // 当前显示图片的http链接
            urls: imgurls // 需要预览的图片http链接列表
          });
    }
    handleChangeCompleteText (completeText) {
        this.setState({
            completeText
          })
    }
    async actPeoperClick(e){
        this.setState({
            hangePeoperid:e
        })
        //处理切换处理人的动作
    }
    async handleClickNow(){
        this.setState({
            hangState:false
        })
        //管理员接受工单处理
        await getOrderHand({id:this.state.data.id,statue:this.state.data.statue+1});//接受处理
        Taro.showToast({
            title : "处理成功",
            icon : 'success' ,
            mask : true,
        })
        let id = this.state.data.id;
        setTimeout(function(){
            Taro.redirectTo({
                url:"order-detail?id="+id
            });
        },1000)
    }
    onCancelModal(){
        this.setState({
            hangState:false,
            handleWaitState:false,
        })
        console.log("------->")
    }
    
    async handleClickWaitS1(){
        //稍等处理
        this.setState({
            hangState:false,
            handleWaitState:true,
        })
    }
    async handleClickCompllete(){
        if(this.state.completeText==""){
            Taro.showToast({
                title : '请输入处理意见' ,
                icon : 'error' ,
                mask : true
            })
            return ;
        }
        //管理员完成提交
        await getOrderHand({
            id:this.state.data.id,
            statue:this.state.data.statue+1,
            opinionPics:this.state.complletePics,
            opinion:this.state.completeText
        });//接受处理
        Taro.showToast({
            title : "处理成功",
            icon : 'success' ,
            mask : true,
        })
        let id = this.state.data.id;
        setTimeout(function(){
            Taro.redirectTo({
                url:"order-detail?id="+id
            });
        },1000)
    }
    async handleClickChangePeroper(){
        //向后台处理 切换处理人员请求
        let hangePeoperid = this.state.hangePeoperid;
        if(hangePeoperid > 0){
            await actionOrderPeroperHand({id:this.state.data.id,hangePeoperid:hangePeoperid});//接受处理
            Taro.showToast({
                title : "切换成功",
                icon : 'success' ,
                mask : true,
            })
            let id = this.state.data.id;
                setTimeout(function(){
                    Taro.redirectTo({
                        url:"order-detail?id="+id
                    });
                },1000)
            return
        }
        Taro.showToast({
            title : "系统参数错误",
            icon : 'error' ,
            mask : true,
        })
    }
    async handleClickWaitS2(){
        //稍等处理2
        //管理员接受工单处理
        let waitTime = this.state.dateSel+" "+this.state.timeSel;

        await getOrderHand({id:this.state.data.id,statue:this.state.data.statue+1,waitTime:waitTime});//接受处理
        Taro.showToast({
            title : "处理成功",
            icon : 'success' ,
            mask : true,
        })
        let id = this.state.data.id;
        setTimeout(function(){
            Taro.redirectTo({
                url:"order-detail?id="+id
            });
        },1000)
    }
    async handleActionListdo(key){
        //立即处理
        this.setState({
            hangState:false
        })
        //管理员接受工单处理
        await getOrderHand({id:this.state.data.id,statue:this.state.data.statue+1,level:key});//接受处理
        Taro.showToast({
            title : "处理成功",
            icon : 'success' ,
            mask : true,
        })
        let id = this.state.data.id;
        setTimeout(function(){
            Taro.redirectTo({
                url:"order-detail?id="+id
            });
        },1000)
    }
    async handleTabBarClick (value) {
        let openid = Auth.getOpenid();
        if(this.state.data.toOpenid == openid){
            if(value === 0 && this.state.data.statue == 0){
                this.setState({
                    hangState:true,
                }) 
            }else if(value === 0 && this.state.data.statue == 1){
                //完成操作
                this.setState({
                    handleCompleteState:true,
                }) 
            }
            console.log(this.state.data.statue );
            return 
        }
        if( this.state.data.fromOpenid!=openid &&this.state.data.toOpenid2 == openid){
            //二级管理员
            if(this.state.data.statue === 0){
                //切换处理人员
                this.setState({
                    hangePeoperIsOpened:true
                })
                return 
            }
        }
        if(this.state.data.statue === 2){
            if(value === 0){
                //评论
            }else if(value === 1){
                //点赞
                await upOrderLike(this.state.data.id);
                // var tabList = [
                //     { title: '评论',iconType: 'message'},
                //     { title: '点赞',iconType: 'heart-2'}
                // ]
                // this.setState({
                //     tabList:tabList
                // })
            }
        }else{
            if(value === 0){
                Taro.navigateTo({
                    url:"order-detail-edit"
                });
            }else if(value === 1){
                if(this.state.data.statue > 0){
                    Taro.showToast({
                        title : '管理员已经在处理，不能编辑' ,
                        icon : 'error' ,
                        mask : true
                    })
                    return false
                }
                Taro.navigateTo({
                    url:"order-detail-edit?id="+this.state.data.id
                });
            }else{
                alert("todo 处理时间")
            }
        }
        
    }
    onTelCall () {
        Taro.makePhoneCall({
            phoneNumber: this.state.data.mobile
        })
    }
    onChangeComplletePics(pics){
        var complletePics = []
        pics.forEach(async item=>{
            let pic_url;
            if(item.file){
                let res = await requestFileUpload( 
                    `/api/file/localUpload/1` ,
                    item.file.path
                )
                pic_url = res.url;
            }else{
                pic_url = item.url;
            }
            
            complletePics.push({url: pic_url});

            this.setState({
                complletePics:complletePics
            })
        })
        
        
    }
    render() {
        let picEtl = (<View className='at-article__p' style="color:#000">--</View>);

        if(this.state.pics.length>0){
            picEtl = (<AtImagePicker
            mode='widthFix'
            showAddBtn={false}
            files={this.state.pics}
            onFail={this.onFail.bind(this)}
            onImageClick={this.onImageClick.bind(this)}
            />)
        }
        let stateHtml = "";
    
        let bottomBat = "";
        if(this.state.tabList.length>0){
            bottomBat = (
                <AtTabBar
                    fixed
                    backgroundColor={this.state.backgroundColor}
                    selectedColor="#333"
                    onClick={this.handleTabBarClick.bind(this)}
                    tabList={this.state.tabList}/>
            );
        }
        
        let completeText = ""
        if(this.state.data.statue === 0){
            //等待管理员处理
            stateHtml = (
                <View className='at-article__info' style="color:#c39862;">
                等待【{this.state.data.toUserObj.actualName}】处理
                </View>);
        }
        else if(this.state.data.statue === 1){
            //正在处理
            stateHtml = (<View>
                <View className='at-article__info' style="color:#67c362;">
                【{this.state.data.toUserObj.actualName}】正在处理
                </View>
                <View className='at-article__info' style="color:#F44336;">
                    【{this.state.data.levelDesc}】预计完成时间：{this.state.data.waitTime}
                </View>
                </View>
                );
        }
        else if(this.state.data.statue === 2){
            //完成
            stateHtml = (
                <View className='at-article__info' style="color:#969696;">
                【{this.state.data.toUserObj.actualName}】完成该工单
                </View>);
            bottomBat = "";
            let cList = this.state.data.detailList.map(e=>{
                return {
                    title:e.createTime,
                    content:[e.handOpinions],
                    icon: 'clock'
                }
            });
            let picEtlxxx=""
            if(this.state.picsComplete.length>0){
                picEtlxxx = (<AtImagePicker
                mode='widthFix'
                showAddBtn={false}
                files={this.state.picsComplete}
                onFail={this.onFail.bind(this)}
                onImageClick={this.onImageClick3.bind(this)}
                />)
            }
            
            completeText = (<Container style="margin: 15px 10px 0;padding: 10px;">
                <AtModalHeader>处理内容</AtModalHeader>
                <AtTimeline 
                pending 
                items={cList}
                >
                </AtTimeline>{picEtlxxx}
                </Container>);

        }
        let handleCompleteStateText=""
        if(this.state.handleCompleteState){
            handleCompleteStateText = (<AtModal isOpened={this.state.handleCompleteState} onCancel={this.onCancelModal.bind(this)}>
            <AtModalHeader>工单完成</AtModalHeader>
            <AtModalContent>
                <AtTextarea
                    value={this.state.completeText}
                    onChange={this.handleChangeCompleteText.bind(this)}
                    maxLength={200}
                    placeholder='你的处理方案...'
                />
                <AtImagePicker
                    mode='widthFix'
                    files={this.state.complletePics}
                    onChange={this.onChangeComplletePics.bind(this)}
                    onFail={this.onFail.bind(this)}
                    onImageClick={this.onImageClick2.bind(this)}
                    />
            </AtModalContent>
            <AtModalAction> <AtButton type='primary' onClick={this.handleClickCompllete.bind(this)}>提交</AtButton> </AtModalAction>
        </AtModal>)
        }

        return (
            <View style="background:#f3f3f3;padding-bottom: 10rpx;">
                <AtModal isOpened={this.state.hangePeoperIsOpened}>
                    <AtModalHeader>选择新的处理人</AtModalHeader>
                    <AtModalContent>
                    {this.getHangePeoperIsOpenedView()}
                    </AtModalContent>
                    <AtModalAction><AtButton onClick={this.handleClickChangePeroper.bind(this)} type='primary' size='small'>确定</AtButton></AtModalAction>
                </AtModal>
                <AtToast isOpened={this.state.toastState} text={this.state.toastText} status="error"></AtToast>
                {handleCompleteStateText}
                <AtModal isOpened={this.state.handleWaitState} onCancel={this.onCancelModal.bind(this)}>
                    <AtModalHeader>预计完成时间</AtModalHeader>
                    <AtModalContent>
                    <Picker onCancel={this.onCancelModal.bind(this)} mode='date' onChange={this.onDateChange.bind(this)}>
                        <AtList>
                        <AtListItem title='请选择日期' extraText={this.state.dateSel} />
                        </AtList>
                    </Picker>
                    <Picker onCancel={this.onCancelModal.bind(this)} mode='time' onChange={this.onTimeChange.bind(this)}>
                        <AtList>
                        <AtListItem title='请选择时间' extraText={this.state.timeSel} />
                        </AtList>
                    </Picker>
                    </AtModalContent>
                    <AtModalAction> <AtButton onClick={this.handleClickWaitS2.bind(this)}>确定</AtButton> </AtModalAction>
                </AtModal>
                <AtActionSheet onCancel={this.onCancelModal.bind(this)} isOpened={this.state.hangState} cancelText='取消' title='请选择工单程度' onCancel={ this.handleCancel } onClose={ this.handleClose }>
                    {this.handleActionList()}
                </AtActionSheet>
                <View style="margin-bottom:150rpx">
                    <Container style="padding: 20rpx;border-bottom: 1px solid #ccc;background:white">
                        <View className='at-article__h2'>
                            {this.state.data.title}
                        </View>
                        <View className='at-article__info' style="line-height: 55rpx;">
                            {this.state.data.typeObj?.label}&nbsp;&nbsp;&nbsp;{this.state.data.actualName}
                        </View>
                        {stateHtml}
                    </Container>
                    {completeText}
                    <Container style="margin: 15px 10px 0;padding: 10px;">
                        <View className="d-rows">
                            <View className='at-article__h3' style="color:#999">工单编号</View>
                            <View className='at-article__h3' >{this.state.data.no}</View>
                        </View>
                        <View className="d-rows">
                            <View className='at-article__h3' style="color:#999">所在部门</View>
                            <View className='at-article__h3' >{this.state.data.departmentObj?.name}</View>
                        </View>
                        <View className="d-rows">
                            <View className='at-article__h3' style="color:#999">联系方式</View>
                            <View className='at-article__h3' onClick={this.onTelCall.bind(this)}>{this.state.data.mobile}</View>
                        </View>
                        <View className="d-rows">
                            <View className='at-article__h3' style="color:#999">问题描述</View>
                            <View className='at-article__p' style="color:#000;white-space: pre-wrap;">
                                {this.state.data.problemDetails}
                            </View>
                        </View>
                        <View className="d-rows">
                            <View className='at-article__h3' style="color:#999">图片</View>
                            <View>
                                {picEtl}
                            </View>
                        </View>
                        <View className="d-rows">
                            <View className='at-article__info' style="color:#999">提交时间</View>
                            <View className='at-article__info' style="color:#000">{this.state.data.createTime}</View>
                        </View>
                        {bottomBat}
                    
                    </Container>
                    <Container style="margin: 15rpx 10rpx 0;padding: 5rpx 10rpx 90rpx;">
                        <View className="at-article__h2">最新评论</View>
                        {this.getCommentView()}
                    </Container>
                    
                </View>
                <WqCommentBar id={this.state.data.id}
                    callback={this.updateData.bind(this)}
                    />
            </View>
        )
    }
    handleActionList(){
        return this.state.gongdanImportanceLeve.map((el,index)=>{
            return (<AtActionSheetItem onClick={ this.handleActionListdo.bind(this,el.configKey) }>
            {el.configName}
            </AtActionSheetItem>);
        });
    }
    getCommentItem(cv){
        return (<View className='at-article__section'>
        <View className="at-row at-row__align--center">
            <View className="at-col at-col-1 at-col--auto">
                <AtAvatar image={cv.createObj.employeeObj.thumbAvatar} text={cv.createObj.employeeObj.actualName}></AtAvatar>
            </View>
            <View className="at-col">
                <View className='at-article__info'>
                    &nbsp;&nbsp;&nbsp;{cv.createObj.employeeObj.actualName} {cv.createTime}
                </View>
            </View>
        </View>
        <View className='at-article__p'>
            {cv.content}
        </View>
    </View>);
    }
    getCommentView(){
        if(this.state.data.commentList&&this.state.data.commentList.length>0){
            return (<View>
                {
                    this.state.data.commentList.map((item,index)=>{
                        return this.getCommentItem(item);
                    })
                }
            </View>);
        }
        return (
            <View className='at-article__section'>
                <View className='at-article__info'>暂无评论</View>
            </View>
        )
    }
    getHangePeoperIsOpenedView(){
        let options = [];
        for(let i in this.state.hangePeoper){
            let item = this.state.hangePeoper[i];
            options.push({ label: item.actualName, value: item.id, desc: item.phone },)
        }
        return (<AtRadio options={options}
            value={this.state.hangePeoperid}
            onClick={this.actPeoperClick.bind(this)}
        >
        </AtRadio>);
    }
}